from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from WorkerOrder.settings import SECRET_KEY
from .models import *
# Create your views here.
import jwt
import datetime

class Login(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            if password ==user_obj.password:
                payload = {
                    'user_id' :user_obj.id,
                    'exp':datetime.datetime.utcnow()+datetime.timedelta(hours=1)
                }
                token = jwt.encode(payload=payload,key=SECRET_KEY)
                return Response({'msg':'登录成功','code':200,'token':token,'username':user_obj.username,'user_id':user_obj.id})
            else:
                return Response({'msg': '用户名或密码错误', 'code': 400})
        else:
            return Response({'msg':'用户不存在','code':400})